<script setup lang="ts">

import CopyOutlined from "@ant-design/icons-vue/CopyOutlined";
import {message} from "ant-design-vue";
import KeywordSetting from "~/contentScripts/views/wxt/BatchAddingProducts/components/KeywordSetting.vue";
import ZhixuanKeywordSetting from "~/contentScripts/views/wxt/BatchAddingProducts/components/ZhixuanKeywordSetting.vue";
import AutoSearchKeywords from "~/contentScripts/views/wxt/components/AutoSearchKeywords.vue";
import CustomSearchKeywords from "~/contentScripts/views/wxt/components/CustomSearchKeywords.vue";
import SearchKeywordsPackage from "~/contentScripts/views/wxt/components/SearchKeywordsPackage.vue";
import {WxtBiddingConstraintType, WxtBizCode, WxtUtils} from "~/contentScripts/views/wxt/lib/wxtUtils";
import WxtModal from "~/contentScripts/views/wxt/wxt-modal.vue";

const props = defineProps({
  value: {
    type: Boolean,
    default: false,
  },
  bizCode: {
    type: String as PropType<WxtBizCode>,
    default: WxtBizCode.关键字推广,
  },
  promotionScene: {
    type: String as PropType<WxtBiddingConstraintType>,
    default: WxtBiddingConstraintType.促进全店成交,
  },
  rows: {
    type: Array,
    default: () => []
  },
});
const visible = ref(false);
const data = reactive<any>({
  autoWordList: [],
  wordList: [],
  wordPackageList: [],
  setting: {},
  zhixuanSetting: {},
});
const current = ref(0);
const handle = () => {
  if (props.rows.length === 0) {
    message.error("请选择需要批量处理的数据！");
    return;
  }
  visible.value = true;
}
const confirmData = ref<any[]>([]);
const calcConfirmData = () => {
  confirmData.value = [];
  props.rows.forEach((item: any, index: number) => {
    confirmData.value.push({
      index: index + 1,
      ...item,
      bidwordRequestData: {
        bidwordList: (data.wordList[item.campaignId] ? data.wordList[item.campaignId][item.adgroupId] || [] : []).map((word: any) => ({
          campaignId: item.campaignId,
          adgroupId: item.adgroupId,
          word,
          bidPrice: data.setting.bidType === 'customBid' ? data.setting.bidPrice : data.setting.bidPriceRatio / 100,
          matchScope: 4,
        })).concat((data.autoWordList[item.campaignId + '-' + item.adgroupId] || []).map((word: any) => ({
          campaignId: item.campaignId,
          adgroupId: item.adgroupId,
          word: word.word,
          bidPrice: data.setting.bidType === 'customBid' ? data.setting.bidPrice : (word.bidPrice * (data.setting.bidPriceRatio / 100)).toFixed(2),
          matchScope: 4,
        }))),
      },
      wordpackageRequestData: {
        wordPackageList: (data.wordPackageList.filter((wordPackage: any) => {
          return wordPackage.id.indexOf(item.campaignId + '-' + item.adgroupId) > -1
        })).map((wordPackage: any) => ({
          campaignId: item.campaignId,
          adgroupId: item.adgroupId,
          wordPackageId: wordPackage.wordPackageId,
          wordPackageName: wordPackage.wordPackageName,
          wordPackageType: wordPackage.wordPackageType,
          bidPrice: data.setting.bidType === 'customBid' ? data.setting.bidPrice : (wordPackage.bidPrice * (data.setting.bidPriceRatio / 100)).toFixed(2),
          matchScope: 4,
        })),
      },
      status:0, // 0 等待中 1 添加关键词中 2 添加词包中 3 添加成功 4 添加失败
    })
  })
  console.log(confirmData.value);
  current.value = 1;
}
const startJob = () => {
  current.value = 2;
  confirmData.value.forEach((item:any,index:number)=>{
    confirmData.value[index].status = 1;
    // 添加关键词
    if (item.bidwordRequestData.bidwordList.length){
      WxtUtils.customRequest('https://one.alimama.com/bidword/add.json',props.bizCode,item.bidwordRequestData).then(res=>{

        // if (res.data.success){
          confirmData.value[index].status = 2;
          // 添加词包
          if (item.wordpackageRequestData.wordPackageList.length){
            WxtUtils.customRequest('https://one.alimama.com/wordpackage/add.json',props.bizCode,item.wordpackageRequestData).then(res=>{
              confirmData.value[index].status = 3;
            })
          }else{
            confirmData.value[index].status = 3;
          }
        // }else{
        //   confirmData.value[index].status = 4;
        // }
      })
    }else {
      item.status = 2;
      // 添加词包
      if (item.wordpackageRequestData.wordPackageList.length){
        WxtUtils.customRequest('https://one.alimama.com/wordpackage/add.json',props.bizCode,item.wordpackageRequestData).then(res=>{
          confirmData.value[index].status = 3;
        })
      }else{
        item.status = 3;
      }
    }
  })
};
const copy = (text: string) => {
  navigator.clipboard.writeText(text).then(() => {
    message.success('复制成功')
  }).catch(() => {
    message.error('复制失败')
  });
}
const columns = [
  {
    title: "#",
    dataIndex: 'index',
    width: 60,
  },
  {
    title: '单元名称',
    dataIndex: 'adgroupName',
    dataType: 'custom',
    slot: 'adgroupName',
  },
  {
    title: '关键词数量',
    dataIndex: 'wordNum',
    dataType: 'custom',
    slot: 'wordNum',
    width: 200,
    render: (text: any, record: any) => {
      return `关键词：${record.bidwordRequestData.bidwordList.length}个  词包：${record.wordpackageRequestData.wordPackageList.length}个`;
    }
  }, {
    title: '操作',
    dataType: 'custom',
    slot: 'action',
    width: 100,
    align: 'center',
  }
]
const columns1 = [
  {
    title: "#",
    dataIndex: 'index',
    width: 60,
  },
  {
    title: '单元名称',
    dataIndex: 'adgroupName',
    dataType: 'custom',
    slot: 'adgroupName',
  },
  {
    title: '关键词数量',
    dataIndex: 'wordNum',
    dataType: 'custom',
    slot: 'wordNum',
    width: 200,
    render: (text: any, record: any) => {
      return `关键词：${record.bidwordRequestData.bidwordList.length}个  词包：${record.wordpackageRequestData.wordPackageList.length}个`;
    }
  }, {
    title: '状态',
    dataType: 'custom',
    slot: 'action',
    width: 200,
    align: 'center',
  }
]
</script>

<template>
  <div @click="handle">
    <slot>
      <a-button type="primary" size="small" ghost>添加关键词</a-button>
    </slot>
  </div>
  <wxt-modal title="批量添加关键词" v-model:visible="visible" width="95%">
    <a-steps v-model:current="current">
      <a-step title="添加关键字">
      </a-step>
      <a-step title="结果确认">
      </a-step>
      <a-step title="添加成功">
      </a-step>
    </a-steps>
    <div style="padding-top: 10px" v-if="visible">
      <div v-if="current==0">
        <a-row :gutter="10">
          <a-col style="width: 720px;">
            <AutoSearchKeywords :biz-code="bizCode" v-model:value="data.autoWordList" :rows="rows"/>
          </a-col>
          <a-col flex="1" style="overflow: auto;">
            <CustomSearchKeywords :biz-code="bizCode" v-model:value="data.wordList" :products="rows" :plans="rows"/>
          </a-col>
        </a-row>
        <a-divider style="margin: 10px 0;"/>
        <a-row :gutter="10">
          <a-col style="overflow: auto;" flex="1">
            <SearchKeywordsPackage :biz-code="bizCode" v-model:value="data.wordPackageList" :products="rows"
                                   :plans="rows"
            />
          </a-col>
          <a-col style="width: 900px;">
            <a-row type="flex" :gutter="10">
              <a-col flex="1">
                <!--      // 关键词设置-->
                <KeywordSetting :biz-code="bizCode" v-model:value="data.setting" :plans="rows"/>
              </a-col>
              <!--              <a-col flex="1">-->
              <!--                &lt;!&ndash;          // 流量智选设置&ndash;&gt;-->
              <!--                <ZhixuanKeywordSetting :biz-code="bizCode" v-model:value="data.zhixuanSetting" :plans="rows"/>-->
              <!--              </a-col>-->
            </a-row>
          </a-col>
        </a-row>
      </div>
      <div v-if="current==1">
        <base-table :columns="columns" :data-source="confirmData">
          <template #adgroupName="row">
            <a-row type="flex" class="adgroupName" :gutter="5">
              <a-col>
                <a-popover placement="right">
                  <template #content>
                    <img :src="row.material.imageUrl"
                         style="width: 200px;height: 200px;"
                    />
                  </template>
                  <img :src="row.material.imageUrl"
                       style="width: 60px;height: 60px;border-radius: 5px;"
                  />
                </a-popover>
              </a-col>
              <a-col flex="1" class="title">
                <a-tooltip :title="row.adgroupName">
              <span style="
            overflow: hidden;
            text-overflow: ellipsis;
            display: -webkit-box;
            -webkit-line-clamp: 2;
            line-clamp: 2;
            -webkit-box-orient: vertical;"
              >{{ row.adgroupName }}</span>
                </a-tooltip>
                <div>
                  <a-space>
                    <span style="color: #666;">ID: {{ row.adgroupId }}</span>
                    <CopyOutlined style="color: #1677ff;cursor: pointer;font-size: 12px;"
                                  @click="copy(row.campaignId)"
                    />
                  </a-space>
                </div>
              </a-col>
            </a-row>
          </template>
          <template #wordNum="row">
            <span>
            <a-popover placement="right">
              <template #content>
                <div>
                  <div>
                    <div style="font-size: 12px;color: #222;">关键词：</div>
                    <div v-for="word in row.bidwordRequestData.bidwordList" style="font-size: 12px;color: #666;">
                      {{ word.word }}
                    </div>
                  </div>
                  <div v-if="row.wordpackageRequestData.wordPackageList.length>0">
                    <div style="font-size: 12px;color: #222;">词包：</div>
                    <div v-for="word in row.wordpackageRequestData.wordPackageList"
                         style="font-size: 12px;color: #666;"
                    >
                      {{ word.wordPackageName }}
                    </div>
                  </div>
                </div>
              </template>
              <div>
                <div v-if="row.bidwordRequestData.bidwordList.length>0">
                  <div style="font-size: 12px;color: #666;">关键词数：{{row.bidwordRequestData.bidwordList.length}}</div>
                </div>
                <div v-if="row.wordpackageRequestData.wordPackageList.length>0">
                  <div style="font-size: 12px;color: #666;">词包数：{{row.wordpackageRequestData.wordPackageList.length}}</div>
                </div>
              </div>
            </a-popover>
            </span>
          </template>
          <template #action="row">
            <a-space>
              <a-button type="primary" danger size="small" @click="()=>{
                // 从确认列表中删除 此index
                const index = confirmData.findIndex((item:any)=>item.index===row.index);
                if(index!==-1){
                  confirmData.splice(index,1);
                }
              }"
              >删除
              </a-button>
            </a-space>
          </template>
        </base-table>
      </div>
      <div v-if="current==2">
        <base-table :columns="columns1" :data-source="confirmData">
          <template #adgroupName="row">
            <a-row type="flex" class="adgroupName" :gutter="5">
              <a-col>
                <a-popover placement="right">
                  <template #content>
                    <img :src="row.material.imageUrl"
                         style="width: 200px;height: 200px;"
                    />
                  </template>
                  <img :src="row.material.imageUrl"
                       style="width: 60px;height: 60px;border-radius: 5px;"
                  />
                </a-popover>
              </a-col>
              <a-col flex="1" class="title">
                <a-tooltip :title="row.adgroupName">
              <span style="
            overflow: hidden;
            text-overflow: ellipsis;
            display: -webkit-box;
            -webkit-line-clamp: 2;
            line-clamp: 2;
            -webkit-box-orient: vertical;"
              >{{ row.adgroupName }}</span>
                </a-tooltip>
                <div>
                  <a-space>
                    <span style="color: #666;">ID: {{ row.adgroupId }}</span>
                    <CopyOutlined style="color: #1677ff;cursor: pointer;font-size: 12px;"
                                  @click="copy(row.campaignId)"
                    />
                  </a-space>
                </div>
              </a-col>
            </a-row>
          </template>
          <template #wordNum="row">
            <span>
            <a-popover placement="right">
              <template #content>
                <div>
                  <div>
                    <div style="font-size: 12px;color: #222;">关键词：</div>
                    <div v-for="word in row.bidwordRequestData.bidwordList" style="font-size: 12px;color: #666;">
                      {{ word.word }}
                    </div>
                  </div>
                  <div v-if="row.wordpackageRequestData.wordPackageList.length>0">
                    <div style="font-size: 12px;color: #222;">词包：</div>
                    <div v-for="word in row.wordpackageRequestData.wordPackageList"
                         style="font-size: 12px;color: #666;"
                    >
                      {{ word.wordPackageName }}
                    </div>
                  </div>
                </div>
              </template>
              <div>
                <div v-if="row.bidwordRequestData.bidwordList.length>0">
                  <div style="font-size: 12px;color: #666;">关键词数：{{row.bidwordRequestData.bidwordList.length}}</div>
                </div>
                <div v-if="row.wordpackageRequestData.wordPackageList.length>0">
                  <div style="font-size: 12px;color: #666;">词包数：{{row.wordpackageRequestData.wordPackageList.length}}</div>
                </div>
              </div>
            </a-popover>
            </span>
          </template>
          <template #action="row">
<!--            {{row.status}}-->
            <a-space>
<!--              // 添加状态-->
              <span v-if="row.status===0" style="color: #444444">等待中</span>
              <span v-if="row.status===1" style="color: #07cee5">添加关键词中</span>
              <span v-if="row.status===2" style="color: #07cee5">添加词包中</span>
              <span v-if="row.status===3" style="color: #1677ff">添加成功</span>
              <span v-if="row.status===4" style="color: #ff4d4f">添加失败</span>
            </a-space>
          </template>
        </base-table>
      </div>
    </div>
    <a-divider style="margin-top: 10px;"/>
    <a-row type="flex">
      <a-col flex="1">
      </a-col>
      <a-col>
        <a-space>
          <a-button v-if="current>0 && current<2" @click="()=>current--">上一步</a-button>
          <a-button type="primary" v-if="current==0" @click="()=> calcConfirmData()">下一步</a-button>
          <a-button type="primary" v-if="current==1" @click="()=> startJob()">下一步</a-button>
          <a-button type="primary" v-if="current===2" @click="()=>{current=0;visible=false;}">完成</a-button>
        </a-space>
      </a-col>
      <a-col flex="1">
      </a-col>
    </a-row>
  </wxt-modal>

</template>

<style scoped>

</style>
